<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="登录名称">
        <el-input disabled v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交修改</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <!--  -->
  </el-card>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  data () {
    return {
      ruleForm: {},
      rules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称必须是1-10位的非空字符串',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    ...mapActions('user', ['gitInfo']),

    // 修改表单校验
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //  修改数据
          this.$http
            .put('/my/userinfo', this.ruleForm)
            .then(({ data: res }) => {
              // console.log(res)
              // 如果修改成功
              if (res.code === 0) {
                // 提示用户
                this.$message({
                  message: res.message,
                  type: 'success'
                })
                // 重新获取用户信息
                this.gitInfo()
              } else {
                this.$message.error('修改用户信息失败')
              }
            })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        ...this.UserInfo
      }
    }
  },
  created () {
    // 调用发请求
    this.gitInfo()

    // 浅拷贝
    this.ruleForm = {
      ...this.UserInfo
    }
  },
  computed: {
    ...mapState('user', ['UserInfo'])
  },
  // 监听传过来变化立即执行
  watch: {
    UserInfo: {
      handler (val) {
        this.ruleForm = {
          ...val
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
